package bobaini.com.dead_exchange;

import bobaini.com.util.RabbitMqUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: Consumer01
 * author: bob.ly
 * Version: 1.0.0
 * DateTime: 2021/07/25-22:44:00
 * Description:假设当前是正常队列, 只是将消息存放到死信队列中.
 */
public class Consumer01 {
    private static final String NORMAL_EXCHANGE = "normal_exchange";
    private static final String DEAD_EXCHANGE = "dead_exchange";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMqUtils.getChannel();
        /**
         * 声明死信交换机和普通交换机
         */
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);

        /**
         * 正常队列绑定死信队列信息
         * 正常队列设置死信交换机 参数 key 是固定值
         * 正常队列设置死信 routing-key 参数 key 是固定值
         * 设置最长长度
         */
        Map<String, Object> params = new HashMap<>();
        params.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        params.put("x-dead-letter-routing-key", "lisi");
//        params.put("x-max-length", 6);
        /**
         * 声明正常队列
         */
        channel.queueDeclare("normal-queue", false, false, false, params);
        channel.queueBind("normal-queue", NORMAL_EXCHANGE, "zhangsan");

        /**
         * 声明死信队列
         */
        channel.queueDeclare("dead-queue", false, false, false, null);
        channel.queueBind("dead-queue", DEAD_EXCHANGE, "lisi");


        DeliverCallback deliverCallback = (tag, message) -> {
            String s1 = new String(message.getBody(), "UTF-8");
            if (s1.equals("info5")) {
                System.out.println("Consumer01 接收到消息" + message + "并拒绝签收该消息");
                //requeue 设置为 false 代表拒绝重新入队 该队列如果配置了死信交换机将发送到死信队列中
                channel.basicReject(message.getEnvelope().getDeliveryTag(), false);
            } else {
                System.out.println("Consumer01 接收到消息" + message);
                channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
            }
            System.out.println("消费者接受到普通队列的消息:" + s1);
        };
        channel.basicConsume("normal-queue", false, deliverCallback, c -> {
        });
    }
}
